package com.jblv.frame.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * @author happyonion.yangtao
 * @version 1.0
 * @title SortListUtils
 * @projectName jblv-frame
 * @packageName com.jblv.frame.common.utils
 * @description 排序工具类
 * @date Create at 2020/6/3 10:31
 * @since jdk1.8
 */
public class SortListUtils<E> {
    private static final Logger logger = LoggerFactory.getLogger(SortListUtils.class);

    /**
     *
     * @param list 是需要排序的list
     * @param method 排序字段的get方法，例如，我我需要根据id排序，就传getId
     * @param sort  升序asc,降序 desc
     *
     * 调用示例：
     *        List<OrderInfoBean> orderInfoBeans = commitOrderDto.getValue();
     *        SortListUtils<OrderInfoBean> sortList = new SortListUtils<OrderInfoBean>();
     *        sortList.Sort(orderInfoBeans, "getCreateTime", "desc");
     */
    public void Sort(List<E> list, final String method, final String sort) {
        Collections.sort(list, new Comparator() {
            public int compare(Object a, Object b) {
                int ret = 0;
                try {
                    Method m1 = ((E) a).getClass().getMethod(method, null);
                    Method m2 = ((E) b).getClass().getMethod(method, null);
                    if (sort != null && "desc".equals(sort))// 倒序
                        ret = m2.invoke(((E) b), null).toString()
                                .compareTo(m1.invoke(((E) a), null).toString());
                    else
                        // 正序
                        ret = m1.invoke(((E) a), null).toString()
                                .compareTo(m2.invoke(((E) b), null).toString());
                } catch (NoSuchMethodException ne) {
                    System.out.println(ne);
                } catch (IllegalAccessException ie) {
                    System.out.println(ie);
                } catch (InvocationTargetException it) {
                    System.out.println(it);
                }
                return ret;
            }
        });
    }


//    public static void main(String[] args) {
//        List<OrderInfoBean> orderInfoBeans = commitOrderDto.getValue();
//        SortListUtils<OrderInfoBean> sortList = new SortListUtils<OrderInfoBean>();
//        sortList.Sort(orderInfoBeans, "getCreateTime", "desc");
//    }
}
